package com.faner.fast.excel.context;

import cn.hutool.core.map.MapUtil;
import com.faner.fast.excel.annotation.ExcelListener;
import com.faner.fast.excel.event.AnalysisEventAutoListener;
import com.faner.fast.excel.kit.ExcelException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@Slf4j
public class ExcelListenerContext {

    public ExcelListenerContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    private ApplicationContext applicationContext;

    private Map<String, AnalysisEventAutoListener> excelListenerMap = MapUtil.newHashMap();

    private void init() {
        log.info("initialization ExcelListenerContext.init() method");
        Map<String, Object> excelListenerAnnotation = applicationContext.getBeansWithAnnotation(ExcelListener.class);
        for (Object bean : excelListenerAnnotation.values()) {
            ExcelListener annotation = bean.getClass().getAnnotation(ExcelListener.class);
            if (excelListenerMap.containsKey(annotation.value())) {
                throw new ExcelException("@ExcelListener value() is not repeatable");
            }
            excelListenerMap.put(annotation.value(), (AnalysisEventAutoListener) bean);
        }
        log.info("---excelListenerMap:{}",excelListenerMap);
    }

    public AnalysisEventAutoListener getEventListener(String type) {
        return this.getEventListener(type, null);
    }

    public AnalysisEventAutoListener getEventListener(String type, HttpServletResponse response) {
        if (excelListenerMap.containsKey(type)) {
            AnalysisEventAutoListener listener = excelListenerMap.get(type);
            listener.setResponse(response);
            return listener;
        }
        throw new ExcelException("参数不合法！");
    }

}
